import React, { useEffect, useState } from 'react'
import { List, Dialog, Button, Input, Toast, Space, Skeleton, Switch } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import TopNavbar from '../../components/TopNavbar'
import styles from './index.module.css'
import { fetchSettingsOverview, requestSmsCode, changePhone } from '../../services/settingsService'
import { logout, selectUser } from '../../store/slices/authSlice'

const Settings = () => {
  const navigate = useNavigate()
  const dispatch = useDispatch()
  
  // 从Redux获取用户信息
  const user = useSelector(selectUser)
  
  // 组件状态
  const [loading, setLoading] = useState(true)
  const [overview, setOverview] = useState(null)
  const [smsCooldown, setSmsCooldown] = useState(0)

  useEffect(() => {
    fetchSettingsOverview().then(setOverview).finally(() => setLoading(false))
  }, [])

  useEffect(() => {
    if (smsCooldown <= 0) return
    const t = setTimeout(() => setSmsCooldown(smsCooldown - 1), 1000)
    return () => clearTimeout(t)
  }, [smsCooldown])

  const handleChangePhone = async () => {
    const phone = await Dialog.prompt({ content: '请输入新手机号', confirmText: '下一步', inputType: 'tel' })
    if (!phone) return
    if (smsCooldown > 0) return
    await requestSmsCode(phone)
    setSmsCooldown(60)
    const code = await Dialog.prompt({ content: '已发送验证码，请输入短信验证码', confirmText: '验证', inputType: 'number' })
    if (!code) return
    const res = await changePhone({ phone, code })
    if (res?.success) {
      Toast.show({ content: '更换成功' })
      setOverview({ ...overview, account: { ...overview.account, phoneMasked: phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') } })
    }
  }

  /**
   * 处理退出登录
   * 显示确认对话框，确认后执行登出操作
   */
  const handleLogout = async () => {
    const confirmed = await Dialog.confirm({
      title: '退出登录',
      content: '确定要退出当前账户吗？',
      confirmText: '退出',
      cancelText: '取消'
    })
    
    if (confirmed) {
      try {
        // 显示加载提示
        Toast.show({
          content: '正在退出...',
          icon: 'loading',
          duration: 0
        })
        
        // 执行登出操作
        await dispatch(logout()).unwrap()
        
        // 清除加载提示
        Toast.clear()
        
        // 显示成功提示
        Toast.show({
          content: '已退出登录',
          icon: 'success'
        })
        
        // 跳转到登录页面
        navigate('/login', { replace: true })
      } catch (error) {
        // 清除加载提示
        Toast.clear()
        
        // 显示错误提示
        Toast.show({
          content: error.message || '退出登录失败',
          icon: 'fail'
        })
      }
    }
  }

  /**
   * 处理切换账户
   * 显示确认对话框，确认后跳转到登录页面
   */
  const handleSwitchAccount = async () => {
    const confirmed = await Dialog.confirm({
      title: '切换账户',
      content: '确定要切换到其他账户吗？当前账户将退出登录。',
      confirmText: '切换',
      cancelText: '取消'
    })
    
    if (confirmed) {
      try {
        // 显示加载提示
        Toast.show({
          content: '正在切换账户...',
          icon: 'loading',
          duration: 0
        })
        
        // 执行登出操作
        await dispatch(logout()).unwrap()
        
        // 清除加载提示
        Toast.clear()
        
        // 跳转到登录页面，并传递切换账户标识
        navigate('/login', { 
          replace: true,
          state: { switchAccount: true }
        })
      } catch (error) {
        // 清除加载提示
        Toast.clear()
        
        // 显示错误提示
        Toast.show({
          content: error.message || '切换账户失败',
          icon: 'fail'
        })
      }
    }
  }

  return (
    <div className={styles.page}>
      <TopNavbar title="设置" showBack onBack={() => navigate(-1)} />
      <div className={styles.container}>
        {loading ? (
          <Skeleton.Paragraph animated lineCount={4} />
        ) : (
          <>
            <List header="账号管理">
              <List.Item extra={overview?.account?.phoneMasked} onClick={handleChangePhone}>
                修改手机号
              </List.Item>
              <List.Item onClick={() => Dialog.alert({ content: '修改密码流程占位' })}>修改密码</List.Item>
              <List.Item onClick={() => Dialog.confirm({ content: '确认注销账号？此操作不可恢复' })}>账号注销</List.Item>
              <List.Item extra={overview?.account?.thirdBindings?.wechat ? '已绑定' : '未绑定'}>绑定微信</List.Item>
              <List.Item extra={overview?.account?.thirdBindings?.alipay ? '已绑定' : '未绑定'}>绑定支付宝</List.Item>
            </List>

            <List header="隐私与安全">
              <List.Item onClick={() => Dialog.alert({ content: '个人信息收集与使用说明（占位）' })}>数据隐私声明</List.Item>
              <List.Item extra={<Switch defaultChecked />}>允许消息通知</List.Item>
              <List.Item extra={overview?.cacheSize || '0M'} onClick={() => Toast.show({ content: '缓存已清理' })}>清除缓存</List.Item>
            </List>

            <div className={styles.logoutWrap}>
              <Button block color='danger' onClick={handleLogout}>退出登录</Button>
              <div className={styles.switch} onClick={handleSwitchAccount}>切换账户</div>
            </div>
          </>
        )}
      </div>
    </div>
  )
}

export default Settings


